﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using Oroboros.Save_Data;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace Oroboros
{
    public static class Serializer
    {
        static Serializer() { }

        public static void SetSaveData(string FileName, GameSaveData SaveData)
        {
            try
            {
                XmlSerializer mySerializer = new XmlSerializer(typeof(GameSaveData));
                XmlTextWriter myWriter = new XmlTextWriter(File.Open(FileName, FileMode.Create), Encoding.UTF8);

                myWriter.Formatting = Formatting.Indented;

                mySerializer.Serialize(myWriter, SaveData);
                myWriter.Close();
            }
            catch(Exception e)
            {
                Trace.WriteLine(e.ToString());
                return;
            }
        }

        public static GameSaveData GetSaveData(string FileName)
        {
            try
            {
                XmlSerializer mySerializer = new XmlSerializer(typeof(GameSaveData));
                XmlTextReader myReader = new XmlTextReader(File.OpenRead(FileName));

                if (!mySerializer.CanDeserialize(myReader))
                    throw new Exception("Object cannot be deserialized");

                GameSaveData SaveData = mySerializer.Deserialize(myReader) as GameSaveData;
                myReader.Close();

                return SaveData;

            }
            catch (Exception e)
            {
                Trace.WriteLine(e.ToString());
                return null;
            }
        }

        public static void Backup(string file)
        {
            //Make Backup
            if (string.IsNullOrEmpty(file)) return;
            string backFile = Path.GetDirectoryName(file) + "\\" + Path.GetFileNameWithoutExtension(file) + "_" + DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss") + ".bak";
            if (File.Exists(backFile))
                File.Delete(backFile);
            File.Copy(file, backFile);
        }
    }
}
